<template>
  <div class="w-screen h-screen p-3 box-border">
    <div class="flex w-full h-full">
      <div class="flex-[2] relative">
        <div
          class="flex bg-blue-200/15 px-4 h-16 box-border rounded items-center justify-start text-base text-[#333] font-bold">
          <div class="flex items-center justify-center">
            <el-form :inline="true">
              <el-form-item label="模式">
                <el-select v-model="modeValue" placeholder="请选择" @change="handleModeChange" style="width: 100px">
                  <el-option v-for="item in modeList" :key="item.idx" :label="item" :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item label="分辨率">
                <el-select v-model="resolutionValue" placeholder="请选择" @change="handleResolutionChange"
                  style="width: 120px">
                  <el-option v-for="(item, index) in resolutionList" :key="index" :label="item" :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item label="设置尺寸">
                <el-select v-model="angleValue" placeholder="请选择设置尺寸" @change="handleSetScanSize" style="width: 100px">
                  <el-option label="原始尺寸" value="setScanSize_ori" />
                  <el-option label="A5" value="setScanSize_A5" />
                  <el-option label="卡片" value="setScanSize_card" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div
          class="absolute top-[76px] left-0 bottom-[108px] w-full bg-blue-200/15 rounded flex items-center justify-center">
          <div class="absolute top-3 left-3 text-center text-sm text-[#333] font-bold">
            当前动作：{{ actionValue || "-" }}
          </div>
          <div
            class="absolute top-3 right-3 text-center text-sm text-[#333] font-bold flex items-center justify-center">
            设备名：{{ deviceName }}
          </div>
          <img v-if="isConnected && mainCamera" id="mainCamera" :src="mainCamera" width="640" height="480"
            class="bg-gray-500/10 rounded"></img>
          <!-- <img v-if="isConnected && subCamera" id="subCamera" :src="subCamera" width="240" height="240"
            class="bg-gray-500/10 rounded absolute bottom-4 right-4"></img> -->
          <el-result v-if="!isConnected" title="提示" sub-title="请稍后，视频正在加载中...">
            <template #icon>
              <img src="/assets/image/bg-stop.png" />
            </template>
            <template #extra>
              <el-button type="primary" @click="handleStartVideo">重新打开</el-button>
            </template>
          </el-result>
        </div>
        <div class="flex justify-between absolute bottom-0 left-0 right-0">
          <div class="flex flex-1 bg-blue-200/15 p-4 box-border rounded items-center justify-start">
            <!-- 遮罩层 -->
            <!-- <div v-if="!isMaskShow"
              class="absolute top-0 left-0 w-full h-full bg-black/20 flex flex-col items-center justify-center z-10">
              <div class="text-center text-sm text-[#fff] font-bold">
                正在获取视频流，请稍等...，请勿关闭页面，否则视频流将无法正常显示
              </div>
              <div class="text-center text-sm text-[#fff] font-bold">
                如果长时间无法获取视频流，请检查高拍仪是否正常连接，或者重启高拍仪，关闭页面后重新打开
              </div>
            </div> -->
            <div class="flex flex-col items-center justify-center cursor-pointer w-20" @click="handleStartVideo">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon_start.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">重开视频</div>
            </div>
            <div class="flex flex-col items-center justify-center cursor-pointer w-20" @click="handleStopVideo">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon_stop.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">关闭视频</div>
            </div>
            <div class="flex flex-col items-center justify-center cursor-pointer w-20" @click="handleCropVideo">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon_cb.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">纠偏裁边</div>
            </div>
            <div class="flex flex-col items-center justify-center cursor-pointer w-20" @click="handleShowProperty">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-5" src="/assets/image/icon_toggle_camera.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">属性设置</div>
            </div>
            <el-tooltip placement="top" effect="light">
              <template #content>
                <div class="flex items-center justify-center my-2">
                  <div class="flex flex-col items-center justify-center w-20 cursor-pointer" @click="handleRotateLeft">
                    <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                      <img class="w-6 h-6" src="/assets/image/icon-left-hander.png" />
                    </div>
                    <div class="text-xs text-[#333] mt-2 font-bold">
                      点击左旋
                    </div>
                  </div>
                  <div class="flex flex-col items-center justify-center w-20 cursor-pointer" @click="handleRotateRight">
                    <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                      <img class="w-6 h-6" src="/assets/image/icon-right-hander.png" />
                    </div>
                    <div class="text-xs text-[#333] mt-2 font-bold">
                      点击右旋
                    </div>
                  </div>
                </div>
              </template>
              <div class="flex flex-col items-center justify-center cursor-pointer w-20">
                <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                  <img class="w-5 h-5" src="/assets/image/icon_more.png" />
                </div>
                <div class="text-xs text-[#333] mt-2 font-bold">更多...</div>
              </div>
            </el-tooltip>
          </div>
          <div class="w-40 bg-blue-200/15 p-4 box-border ml-4 rounded flex items-center justify-center">
            <!-- <div v-if="!isMaskShow" class="absolute top-0 left-0 w-full h-full bg-black/20"></div> -->
            <div class="flex flex-col items-center justify-center cursor-pointer w-20" @click="handleTakePicture">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon-camer.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">开始读取</div>
            </div>
          </div>
        </div>
      </div>
      <div class="flex-[1] ml-3 relative">
        <div>
          <div
            class="flex bg-blue-200/15 px-4 h-16 box-border rounded items-center justify-start text-base text-[#333] font-bold">
            图片展示区
          </div>
        </div>
        <div class="absolute top-[76px] left-0 bottom-[108px] w-full bg-blue-200/15 rounded">
          <div class="flex flex-wrap p-4 rounded items-center justify-center">
            <el-image alt="点击预览" v-for="(item, index) in base64PicturesList" :key="index" :src="item.src"
              :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="base64PicturesList" :initial-index="4"
              fit="cover" class="cursor-pointer rounded" />
          </div>
          <div class="p-2 text-center text-xs text-[#333] font-bold">{{ currentIdCardInfo }}</div>
          <div v-if="currentTitle" class="text-center text-xs text-[#333] font-bold mt-2">
            当前操作： {{ currentTitle || "-" }}
          </div>
        </div>
        <div class="flex justify-between absolute bottom-0 left-0 right-0">
          <div class="flex flex-1 bg-blue-200/15 p-4 box-border rounded items-center justify-end">
            <!-- <div v-if="!isMaskShow"
              class="absolute top-0 left-0 w-full h-full bg-black/20 flex flex-col items-center justify-center z-10">
              <div class="text-center text-sm text-[#fff] font-bold">
                请勿关闭页面，否则视频流将无法正常显示
              </div>
            </div> -->
            <div class="flex flex-col items-center justify-center w-20 cursor-pointer" @click="handleShowInfo">
              <div class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400">
                <img class="w-6 h-6" src="/assets/image/icon-info.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">读取信息</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import WebSocketConnection from "../../utils/scoket";
import { QWebChannel } from "../../utils/channel";
let wsConnection; // 连接

const openSocket = () => {
  wsConnection = new WebSocketConnection("ws://127.0.0.1:12345"); // 连接
};

// 打开socket
openSocket();

const webChannel = ref(null);
const mainCamera = ref(""); // 主摄像头
const subCamera = ref(""); // 副摄像头
const deviceName = ref(""); // 设备名
const isConnected = ref(false); // 连接状态
const resolutionList = ref([]); // 分辨率列表
const resolutionValue = ref("2592 * 1944"); // 分辨率值
const modeList = ref([]); // 模式列表
const modeValue = ref("MJPG"); // 模式值
const base64PicturesList = ref([]); // 图片列表
const angleValue = ref("setScanSize_ori"); // 角度值
const actionValue = ref(""); // 操作值
const currentTitle = ref(""); // 当前标题
const currentReadType = ref("1"); // 当前读取类型
const currentIdCardInfo = ref(""); // 当前二代证图像
const isMaskShow = ref(false); // 遮罩层
let loading = null; // 加载状态

// 选择模式
const handleModeChange = () => {
  handleActionChange(`选择模式: ${modeValue.value}`);
  webChannel.value.devChanged("primaryDev_:" + modeValue.value);
};

// 选择分辨率
const handleResolutionChange = () => {
  handleActionChange(`选择分辨率: ${resolutionValue.value}`);
  dialog.devChanged("primaryDev_:" + resolutionValue.value);
};

// 拍照
const handleTakePicture = () => {
  loading = ElLoading.service({
    lock: true,
    text: "拍照中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  handleActionChange("开始读取");
  if (currentReadType.value == 1) {
    // 获取二代证图像
    // Flag 1表示头像，2表示正面，3表示反面，4表示正反垂直合成，
    // 5表示反正垂直合成，6表示正反水平合成，7表示反正水平合成
    webChannel.value.get_functionTypes("getIdcardImage", "5", "", "");
  } else {
    webChannel.value.photoBtnClicked("primaryDev_");
    webChannel.value.get_actionType("savePhotoPriDev");
  }
};

const handleStartVideo = () => {
  console.log("handleStartVideo", deviceName.value);
  webChannel.value.devChanged("primaryDev_:" + deviceName.value);
  isConnected.value = true;
  handleActionChange("重开视频");
};

const handleStopVideo = () => {
  webChannel.value.get_actionType("closePriVideo");
  isConnected.value = false;
  mainCamera.value = "";
  handleActionChange("关闭视频");
};

const handleCropVideo = () => {
  webChannel.value.get_actionType("setdeskew");
  handleActionChange("纠偏裁边");
};

const handleShowProperty = () => {
  handleActionChange("属性设置");
  webChannel.value.get_actionType("showProperty");
  // webChannel.value.devChanged("subDev_:" + deviceName.value);
};

const handleSetScanSize = (value) => {
  webChannel.value.get_actionType(value);
  handleActionChange(`设置图片尺寸: ${value}`);
};

const handleRotateLeft = () => {
  webChannel.value.get_actionType("rotateLeft");
  handleActionChange("左旋");
};

const handleRotateRight = () => {
  webChannel.value.get_actionType("rotateRight");
  handleActionChange("右旋");
};

const handleActionChange = (value) => {
  actionValue.value = value;
};

const handleShowInfo = () => {
  handleActionChange("正在识别信息");
  console.log("handleShowInfo");
  // 判断是否存在
  if (base64PicturesList.value.length > 0) {
    if (currentReadType.value == 1) {
      if (currentIdCardInfo.value) {
        // 获取二代证图像
        const idCardData = parseIdCardData(currentIdCardInfo.value);
        console.log("idCardData", idCardData);
        sendMessage("LTScannerBase64Img", {
          readType: currentReadType.value,
          idCardData: idCardData,
          base64PicturesList: base64PicturesList.value,
        });
        if (wsConnection) {
          wsConnection.close();
        }
      } else {
        ElMessage.error("身份证信息为空");
      }
    } else {
      sendMessage("LTScannerBase64Img", {
        readType: currentReadType.value,
        base64PicturesList: base64PicturesList.value,
      });
      if (wsConnection) {
        wsConnection.close();
      }
    }

  } else {
    console.log("base64PicturesList.value", base64PicturesList.value);
    ElMessage.error("请先拍照");
  }
};

const sendMessage = (action, message) => {
  const parentWindow = window.parent;
  const data = {
    action: action,
    message: message,
  };
  parentWindow.postMessage(JSON.stringify(data), "*");
}

const parseIdCardData = (dataString) => {
  const dataArray = dataString.split(' ');
  return {
    data: {
      name: { value: dataArray[0], label: "姓名" }, // 姓名
      gender: { value: dataArray[1], label: "性别" }, // 性别
      nation: { value: dataArray[2], label: "民族" }, // 民族
      birth: { value: `${dataArray[3]}-${String(dataArray[4]).padStart(2, '0')}-${String(dataArray[5]).padStart(2, '0')}`, label: "生日" }, // 生日
      address: { value: dataArray[6], label: "地址" }, // 地址，动态计算长度
      idNum: { value: dataArray[7], label: "身份证号码" }, // 身份证号码
      location: { value: parseAddress(dataArray[6]), label: '省市区' }
    }
  };
}

const parseAddress = (address) => {
  // 匹配省、市、区/县的正则表达式
  const provinceReg = /^(.+?(?:省|自治区|特别行政区))/;
  const cityReg = /(.+?(?:市|自治州|地区|盟))/;
  const districtReg = /(.+?(?:区|县|旗|市))/;

  let result = {
    province: '',
    city: '',
    district: '',
    detail: ''
  };

  let tempAddress = address;

  // 省市对应关系映射表
  const cityProvinceMap = {
    // 华北地区
    '北京市': '北京市',
    '天津市': '天津市',
    '石家庄市': '河北省',
    '太原市': '山西省',
    '呼和浩特市': '内蒙古自治区',

    // 东北地区
    '沈阳市': '辽宁省',
    '大连市': '辽宁省',
    '长春市': '吉林省',
    '哈尔滨市': '黑龙江省',

    // 华东地区
    '上海市': '上海市',
    '南京市': '江苏省',
    '苏州市': '江苏省',
    '无锡市': '江苏省',
    '杭州市': '浙江省',
    '宁波市': '浙江省',
    '温州市': '浙江省',
    '合肥市': '安徽省',
    '福州市': '福建省',
    '厦门市': '福建省',
    '南昌市': '江西省',
    '济南市': '山东省',
    '青岛市': '山东省',

    // 中南地区
    '郑州市': '河南省',
    '武汉市': '湖北省',
    '长沙市': '湖南省',
    '广州市': '广东省',
    '深圳市': '广东省',
    '珠海市': '广东省',
    '佛山市': '广东省',
    '东莞市': '广东省',
    '南宁市': '广西壮族自治区',
    '海口市': '海南省',

    // 西南地区
    '重庆市': '重庆市',
    '成都市': '四川省',
    '贵阳市': '贵州省',
    '昆明市': '云南省',
    '拉萨市': '西藏自治区',

    // 西北地区
    '西安市': '陕西省',
    '兰州市': '甘肃省',
    '西宁市': '青海省',
    '银川市': '宁夏回族自治区',
    '乌鲁木齐市': '新疆维吾尔自治区',

    // 特别行政区
    '香港特别行政区': '香港特别行政区',
    '澳门特别行政区': '澳门特别行政区'
  }

  // 提取省（如果有）
  const provinceMatch = tempAddress.match(provinceReg);
  if (provinceMatch) {
    result.province = provinceMatch[1];
    tempAddress = tempAddress.replace(provinceMatch[1], '');
  }

  // 提取市（支持地址以市开头的情况）
  const cityMatch = tempAddress.match(cityReg);
  if (cityMatch) {
    // 处理类似"沈阳市阳市"这样的情况，避免重复匹配
    if (tempAddress.startsWith(cityMatch[1])) {
      result.city = cityMatch[1];
      tempAddress = tempAddress.replace(cityMatch[1], '');
    }
  }

  // 提取区县
  const districtMatch = tempAddress.match(districtReg);
  if (districtMatch) {
    result.district = districtMatch[1];
    tempAddress = tempAddress.replace(districtMatch[1], '');
  }

  // 剩余部分作为详细地址
  result.detail = tempAddress.trim();

  // 如果没有省份但有市，尝试根据市推断省份
  if (!result.province && result.city) {
    result.province = cityProvinceMap[result.city] || '';
  }

  return result;
};

const getFromURL = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const token = urlParams.get("token");
  const title = urlParams.get("title");
  const readType = urlParams.get("readType");
  currentTitle.value = title;
  currentReadType.value = readType ? readType : "1";
};

onMounted(() => {
  // 获取参数
  getFromURL();

  wsConnection.onOpen = () => {
    console.log("wsConnection.onOpen");
    handleActionChange("连接成功");

    // 初始化QWebChannel
    new QWebChannel(wsConnection, (channel) => {
      webChannel.value = channel.objects.dialog;
      isConnected.value = true;
      modeList.value = [];
      resolutionList.value = [];
      // 设置打印信息
      webChannel.value.sendPrintInfo.connect((message) => {
        console.log("Received message:", message);
        loading && loading.close();
        if (message.indexOf("priDevName:") >= 0) {
          deviceName.value = message.substr(11);
        }
        if (message.indexOf("priModel:") >= 0) {
          modeList.value.push(message.substr(9));
        }
        if (message.indexOf("priResolution:") >= 0) {
          resolutionList.value.push(message.substr(14));
        }
        if (message.indexOf("idFaceInfo:") >= 0) {
          const value = message.substr(11);
          if (value) {
            base64PicturesList.value = [{ src: "data:image/jpg;base64," + value, info: currentIdCardInfo.value }];
            ElMessage.success("拍照成功");
          }
          return;
        }

        if (message.indexOf("IDcardInfo:") >= 0) {
          const value = message.substr(11);
          console.log("IDcardInfo:value", value);
          if (value) {
            currentIdCardInfo.value = value;
          }
          return;
        }

      });

      // 设置遮罩层
      isMaskShow.value = true;

      // 设置主摄像头
      webChannel.value.send_priImgData.connect((message) => {
        mainCamera.value = "data:image/jpg;base64," + message;
      });

      // 设置副摄像头
      // webChannel.value.send_subImgData.connect((message) => {
      //   subCamera.value = "data:image/jpg;base64," + message;
      // });


      // 设置拍照
      if (currentReadType.value == 2) {
        webChannel.value.send_priPhotoData.connect((message) => {
          loading.close();
          if (message) {
            base64PicturesList.value = [{ src: "data:image/jpg;base64," + message, info: '身份证正面' }];
            ElMessage.success("拍照成功");
          } else ElMessage.error("拍照失败");
        });
      }

      webChannel.value.html_loaded("one");
    });
  };

  wsConnection.onClose = () => {
    isConnected.value = false;
    handleActionChange("连接断开");
    // if (wsConnection.socket.readyState !== WebSocket.OPEN) {
    //   wsConnection.connect();
    // }
  };

  wsConnection.connect();
});

onUnmounted(() => {
  console.log("onUnmounted");
  if (wsConnection) {
    webChannel.value && webChannel.value.get_actionType("closeSignal");
    wsConnection.close();
  }
});

onBeforeUnmount(() => {
  console.log("onBeforeUnmount");
  if (wsConnection) {
    webChannel.value && webChannel.value.get_actionType("closeSignal");
    wsConnection.close();
  }
});

window.onbeforeunload = () => {
  console.log("onbeforeunload");
  if (wsConnection) {
    webChannel.value && webChannel.value.get_actionType("closeSignal");
    wsConnection.close();
  }
};

</script>
<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
